#-------------------------------------------------------------------------------
# Name:	 Parse Tool for AMOS Results
# Purpose:
#
# Author:	  bc6
#
# Created:	 14/02/2012
# Copyright:   (c) bc6 2012
# Licence:	 <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

def convert_file2dictionary(filename,dictKeyField):
	fTasks=open(filename,"r")
	original_lines=fTasks.readlines()
	fTasks.close()
	original_fields=map(lambda s:s.strip('"'),original_lines[0].strip("\n").split("\t"))
	all_tasks=[]

	for t in original_lines[1:]:
		task_dictionary={}
		for k,v in map(None,original_fields,t.split('\t')):
			task_dictionary[k]=v.strip('"').strip('"')
		#all_tasks[task_dictionary[dictKeyField]]=task_dictionary
		all_tasks.append(task_dictionary)
	return all_tasks

def genHTML(image_labels):
	o = open("output.html", "w")
	header = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Results Batch 2</title>
<style type="text/css">
div{
	font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;font-size:12px;background:#fff;margin:1px;float:left;display:block;
}
div:hover{
	background:#CFF;
}

</style>


</head>


<body>
<script src="processing-1.3.6.min.js"></script>
<script type="application/processing" data-processing-target="canvas1">

PImage bigImage;
String image_str = "";
int bs = 3; // this is our dot radius
float[] bx = new float[10];
float[] by = new float[10];

void setup()
{
  for (int i=0; i<10; i++) {
  	bx[i] = 0.0;
  	by[i] = 0.0;
  }
  bigImage = requestImage(cur_image);
  image_str = cur_image;
  size(352, 240);

  ellipseMode(CENTER_RADIUS);
}
void draw()
{
  updateSelf();
	//background(background_image);
  if (bigImage.width == 0) {
	// Image is not yet loaded
  } else if (bigImage.width == -1) {
	// This means an error occurred during image loading
  } else {
	// Image is ready to go, draw it
	background(bigImage);
  }
  //we'll draw dots on the coordinates passed in from our javascript

  	for (i=0; i<10;i++) {
		if(coordx[i]>0) {
			stroke(255);
			//colorMode(RGB,255);
			fill(255 - i*20,i*100%255,i*30%255);
			ellipse(coordx[i], coordy[i], bs, bs);
		}
	}

}
void updateSelf()
{
	String new_image_str = cur_image;
	if (new_image_str != image_str) {
		background(200);
		bigImage = requestImage(cur_image);
		image_str = cur_image;
		/*
		for (int i=0; i<10; i++) {
			bx[i] = coordx[i];
			by[i] = coordy[i];
		}
		*/
	}
}
</script>


<script language="Javascript">
var last_clicked = "";
var cur_image = "http://amosweb.cse.wustl.edu/image/984/20091026_143750.jpg";
var coordx = new Array();
var coordy = new Array();

function plot(args) {
	args_array = args.split(" ");
	document.getElementById(args_array[0]).style.background = "#CFF";
	if (last_clicked != "") {
		document.getElementById(last_clicked).style.background = "#FFF";
	}
	last_clicked = args_array[0];
	cur_image = "http://amosweb.cse.wustl.edu/image/984/".concat(last_clicked);

	coordx = new Array();
	coordy = new Array();
	for (i=0;i<(args_array.length-1);i++) {
		this_coord = args_array[i+1].split(",");
		coordx[i] = this_coord[0];
		coordy[i] = this_coord[1];
	}
	document.getElementById("coord_text").innerHTML = args;
	/*
	for (i=0;i<coordx.length;i++) {
		document.getElementById("coord_text").innerHTML += " " + coordx[i] + "," + coordy[i];
	}*/

function loading() {
	document.getElementById("loading").style.visibility = "visible";
}

function notloading() {
	document.getElementById("loading").style.visibility = "hidden";
}

}
</script>

<canvas id="canvas1"> </canvas><p id="coord_text"></p>

<br />

"""
	o.write('%s<div>'%header)
	for k,v in image_labels.iteritems():
		tmp_str = ""
		for each in v:
			tmp_str = "%s %s" % (tmp_str, each)
		param = "%s %s" % (k, tmp_str[2:])
		o.write('<div id="%s" onclick="javascript:plot(\'%s\')">%s</div>' % (k, param, k))

	o.write("</div></body></html>")

def run():
	FN="amos.results"
	#lines=file(FN,'r').readlines()
	#header=lines[0]
	#attr_names=map(lambda s:s.strip("\"\n"),header.split("\t"))
	#print attr_names

	all_tasks=convert_file2dictionary('amos.results','hitid')


##	not_empty = []
##	for task in all_tasks:
##		if (task['Answer.coords1'] == '') and (task['Answer.coords1'] == '') and (task['Answer.coords1'] == '') and (task['Answer.coords1'] == ''):
##			pass
##		else:
##			not_empty.append(task)
##	print "found %s entries with non-empty results" % len(not_empty)

	tasks = all_tasks
	print("there were %s tasks in the output." % len(tasks))
	image_labels = {}
	for task in all_tasks:
		if (1):
		   if (task['Answer.img_name'] not in image_labels.iterkeys()):
		   	  image_labels[task['Answer.img_name'][:-2]] = [task['Answer.people']]
		   else:
   		   		image_labels[task['Answer.img_name'][:-2]].append(task['Answer.people'])



##		if (task['Answer.coords2'] != ''):
##		   if (task['Answer.img_name2'] not in image_labels.iterkeys()):
##		   	  image_labels[task['Answer.img_name2']] = [task['Answer.coords2']]
##		   else:
##   		   		image_labels[task['Answer.img_name2']].append(task['Answer.coords2'])
##
##		if (task['Answer.coords3'] != ''):
##		   if (task['Answer.img_name3'] not in image_labels.iterkeys()):
##		   	  image_labels[task['Answer.img_name3']] = [task['Answer.coords3']]
##		   else:
##   		   		image_labels[task['Answer.img_name3']].append(task['Answer.coords3'])
##
##		if (task['Answer.coords4'] != ''):
##		   if (task['Answer.img_name4'] not in image_labels.iterkeys()):
##		   	  image_labels[task['Answer.img_name4']] = [task['Answer.coords4']]
##		   else:
##   		   		image_labels[task['Answer.img_name4']].append(task['Answer.coords4'])


##		for k,v in image_labels.iteritems():
##			print "%s: %s" % (k,v)
	print "found %s images with labels" % len(image_labels)
	genHTML(image_labels)

def main():
	run()

if __name__ == '__main__':
	main()
